package cn.sciento.transfer.infra.datasource.config;

import java.util.List;
import cn.sciento.transfer.infra.datasource.DynamicRoutingDataSource;
import cn.sciento.transfer.infra.datasource.provider.AbstractDataSourceProvider;
import cn.sciento.transfer.infra.datasource.provider.DefaultDataSourceProvider;
import cn.sciento.transfer.infra.datasource.provider.TransferDataSourceProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties({DataSourceProperties.class})
@AutoConfigureBefore({DataSourceAutoConfiguration.class})
public class DynamicRoutingDataSourceConfig {
  @Autowired
  private DataSourceProperties dataSourceProperties;
  
  @Bean
  @ConditionalOnMissingBean
  public DefaultDataSourceProvider defaultDataSourceProvider() {
    return new DefaultDataSourceProvider(this.dataSourceProperties);
  }
  
  @Bean
  @ConditionalOnMissingBean
  public TransferDataSourceProvider transferDataSourceProvider() {
    return new TransferDataSourceProvider();
  }
  
  @Bean
  @ConditionalOnMissingBean
  public DynamicRoutingDataSource dynamicRoutingDataSource(List<AbstractDataSourceProvider> abstractDataSourceProviderList) {
    return new DynamicRoutingDataSource(abstractDataSourceProviderList);
  }
}
